package com.nd.qa.shareplate.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//import com.alibaba.fastjson.JSONObject;
import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.jenkins.JenkinsPoster;
import com.nd.qa.shareplate.model.InterfaceEnvironment;
import com.nd.qa.shareplate.model.InterfaceInfo;
import com.nd.qa.shareplate.model.InterfaceProject;
import com.nd.qa.shareplate.model.JobData;
import com.nd.qa.shareplate.model.ShareJob;
import com.nd.qa.shareplate.service.InterfaceEnvironmentService;
import com.nd.qa.shareplate.service.InterfaceProjectService;
import com.nd.qa.shareplate.service.InterfaceService;
import com.nd.qa.shareplate.service.LoginService;
import com.nd.qa.shareplate.service.ShareJobService;
import com.nd.qa.shareplate.service.UnitService;
import com.nd.qa.shareplate.util.FormatTimeUtil;
import com.nd.qa.shareplate.util.HttpRequestUtils;
import com.nd.qa.shareplate.util.JsonUtil;

import net.sf.json.JSONObject;

/**
 * 测试报告
 * @author huangjian
 * @version V1.0
 */
@Controller
@RequestMapping("/report/*")
public class ReportController {

	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.LoginService")
	private LoginService loginService;
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.InterfaceService")
	private InterfaceService interfaceService;
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.UnitService")
	private UnitService unitService;
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ShareJobService")
	private ShareJobService shareJobService;
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.InterfaceProjectService")
	private InterfaceProjectService interfaceProjectService;
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.InterfaceEnvironmentService")
	private InterfaceEnvironmentService interfaceEnvironmentService;
	
	
	private ResourceBundle rb = ResourceBundle.getBundle("properties/configuration");
	/**
	 * 获取首页数据
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		//分别获取测试类型一周通过率(入参带上时间)
		/*interfaceService.queryAllInterface();
		interfaceService.querySuccessInterface();
		unitService.queryAllUnit();
		unitService.querySuccessUnit();*/
		//分别获取一周成功率分别情况
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		if (sessionUserInfo==null) {
			return "/main/login";
		}
		//查询结果集
		ShareJob shareJob = new ShareJob();
		shareJob.setUserName(sessionUserInfo.getUserName());
		/*List<ShareJob> jobList = shareJobService.queryJob(shareJob);
		if (jobList.size()>0) {
			shareJob = jobList.get(0);
		}*/
		//查询测试项目信息
		List<InterfaceProject> projects = interfaceProjectService.queryInterfaceProject();
		//查询项目信息
		List<ShareJob> jobsList = shareJobService.queryLimitJob(shareJob);
		model.addAttribute("job", shareJob);
		model.addAttribute("projects", projects);
		model.addAttribute("jobsList", jobsList);
		//分别获取总的测试通过率(全部用例)
		return "/main/report";
	}
	/**
	 * 查询项目环境
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 */
	@RequestMapping("/getProjectEnvironment")
	public void getProjectEnvironment(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		int projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
		 //Jenkins服务请求
		JSONObject json = new JSONObject();
		Map<String, Object> result = new HashMap<String,Object>();
		response.setContentType("application/json;charset=UTF-8");
		InterfaceEnvironment interfaceEnvironment = new InterfaceEnvironment();
		interfaceEnvironment.setProjectId(projectId);
		List<InterfaceEnvironment> environments = interfaceEnvironmentService.queryEnvironmentsById(interfaceEnvironment);
		try {
			result.put("environments", environments);
			json.put("code", 0);
			json.put("result", result);
			response.getWriter().print(json);
			response.getWriter().flush();
		    response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	     
	}
	@RequestMapping("/getUnitReportPage")
	public String getUnitReportPage(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		if (sessionUserInfo==null) {
			return "/main/login";
		}
		//查询头部菜单
		List<HashMap<String, Object>> menuList=null;
		try {
			menuList = loginService.queryHeaderMenuFunction();
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("menuList", menuList);
		return "/main/report-unit";
	}
	
	
	@RequestMapping("/getInterReportPage")
	public String getInterReportPage(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		if (sessionUserInfo==null) {
			return "/main/login";
		}
		//查询头部菜单
		List<HashMap<String, Object>> menuList=null;
		List<HashMap<String, Object>> typeList = null;
		List<HashMap<String, Object>> reasonList = null;
		List<InterfaceInfo> interList = null;
		try {
			menuList = loginService.queryHeaderMenuFunction();
			//
			typeList = interfaceService.queryInterErrorType();
			//reasonList = interfaceService.queryInterErrorReason();
			interList = interfaceService.querytotalInterface();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		String typeStr = JsonUtil.toString(typeList);
		model.addAttribute("menuList", menuList);
		model.addAttribute("typeList", typeList);
		model.addAttribute("interList", interList);
		model.addAttribute("typeStr", typeStr);
		return "/main/report-interface";
	}
	
	@RequestMapping("/queryInterError")
	public String queryInterError(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		List<InterfaceInfo> interList = null;
		try {
			String querytext = String.valueOf(inParam.get("querytext"));
			InterfaceInfo info = new InterfaceInfo();
			info.setErrorSimpleDetail(querytext);
			interList = interfaceService.queryInterError(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("interList", interList);
		return "/main/errorlist";
	}
	@RequestMapping("/showInterFailError")
	public String showInterFailError(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		List<InterfaceInfo> interList = null;
		try {
			String resultStatus = String.valueOf(inParam.get("resultStatus"));
			InterfaceInfo info = new InterfaceInfo();
			info.setResultStatus(Integer.valueOf(resultStatus));
			interList = interfaceService.queryInterError(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("interList", interList);
		return "/main/errorlist";
	}
	
	@RequestMapping("/getInterReportDetail")
	public String getInterReportDetail(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		List<InterfaceInfo> interList = null;
		try {
			Integer interfaceId = Integer.valueOf(String.valueOf(inParam.get("interfaceId")));
			InterfaceInfo info = new InterfaceInfo();
			info.setInterfaceId(interfaceId);
			interList = interfaceService.queryInterError(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/main/errordetail";
	}
	/**
	 * 一键触发测试构建
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/triggerKey")
	@ResponseBody
	public void triggerKey(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		String environmentId = String.valueOf(inParam.get("environmentId"));
		String environmentDesc = String.valueOf(inParam.get("ucEnvironmentDesc"));
		String environmentUrl = String.valueOf(inParam.get("environmentUrl"));
		String environmentName = String.valueOf(inParam.get("environmentName"));
		InterfaceEnvironment interfaceEnvironment = new InterfaceEnvironment();
		interfaceEnvironment.setEnvironmentId(Integer.valueOf(environmentId));
		if (!"".equals(environmentId)&&environmentId!=null) {
			//查询测试环境信息
			interfaceEnvironment = interfaceEnvironmentService.queryEnvironmentById(interfaceEnvironment);
		}
		String user = interfaceEnvironment.getEnvironmentUser();
		 //Jenkins服务请求
		JSONObject json = new JSONObject();
		response.setContentType("application/json;charset=UTF-8");
		//是否存在未结束的job
		String lastUrl = rb.getString("uc.jenkins.lastjob.lasturl");
		String currentJobUrl = rb.getString("uc.jenkins.currentjob.url");
		/*String preUrl = rb.getString("uc.jenkins.lastjob.preurl");
		String jobName = null;
		if ("1".equals(environmentType)) {
			jobName = rb.getString("uc.jenkins.production.jobname");
		}else if ("2".equals(environmentType)) {
			jobName = rb.getString("uc.jenkins.preproduction.jobname");
		}else if ("3".equals(environmentType)) {
			jobName = rb.getString("uc.jenkins.test.jobname");
		}else if ("4".equals(environmentType)) {
			jobName = rb.getString("uc.jenkins.virtual.jobname");
		}else {
			jobName = rb.getString("uc.jenkins.aws.jobname");
		}*/
		String jobName = environmentUrl.substring(environmentUrl.lastIndexOf("/")+1, environmentUrl.length());
		String strResult = HttpRequestUtils.httpGet(environmentUrl+lastUrl);
		//解析结果集
		JSONObject jsonResult = JSONObject.fromObject(strResult);
		JSONObject lastJson = (JSONObject) jsonResult.get("lastBuild");
		JSONObject lastComJson = (JSONObject) jsonResult.get("lastCompletedBuild");
		String username = user.split(":")[0];//rb.getString("uc.jenkins.username");
        String password = user.split(":")[1];//rb.getString("uc.jenkins.password");
        String jenkinsServer = environmentUrl.substring(0, environmentUrl.lastIndexOf(":"));//rb.getString("uc.jenkins.jenkinsServer");
        String buildToken = rb.getString("uc.jenkins.buildToken");
        String port = environmentUrl.substring(environmentUrl.lastIndexOf(":")+1, environmentUrl.lastIndexOf(":")+5);//rb.getString("uc.jenkins.port");
        JobData jd = new JobData();
        jd.setUsername(username);//604524
        jd.setPassword(password);//"123456"
        //jd.setToken(buildToken);
        jd.setJobName(jobName);//jobName
        jd.setServer(jenkinsServer);
        jd.setPort(port);
        JenkinsPoster jp ;
        if (environmentUrl.contains("jenkins")) {
        	jp = new JenkinsPoster(jd,"jenkins");
		}else{
			jp = new JenkinsPoster(jd,"");
		}
		 try {
			 if (lastJson.get("number").equals(lastComJson.get("number"))) {
				 jp.postJenkinsJob();
				 //获取目前最后一次build id
				 String currentBuildId = HttpRequestUtils.httpGet(environmentUrl+currentJobUrl);
				 currentBuildId = String.valueOf(Integer.parseInt(currentBuildId)+1);
				 //将job信息录入到数据库
				 ShareJob shareJob = new ShareJob();
				 shareJob.setUserName(sessionUserInfo.getUserName());
				 shareJob.setBuildId(currentBuildId);
				 shareJob.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
				 shareJob.setJobType("uc");
				 shareJob.setJobStatus("building");
				 shareJob.setJobDesc("true");
				 shareJob.setEnvironmentDesc(environmentName);
				 shareJob.setEnvironmentUrl(environmentUrl);
				 shareJob.setStatus("A");
				 shareJobService.insertJob(shareJob);
				json.put("code", "0");
				json.put("currentBuildId", currentBuildId);
				json.put("environmentUrl", environmentUrl);
				json.put("environmentName", environmentName);
				json.put("msg", "一键拨测成功");
			 }else{
				 json.put("code", "-1");
				 json.put("msg", "服务正忙，客官请稍后再来！");
			 }
             response.getWriter().print(json);
             response.getWriter().flush();
             response.getWriter().close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 定时请求
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/refreshState")
	@ResponseBody
	public void refreshState(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		final String buildId = String.valueOf(inParam.get("buildId"));
		String environmentUrl = String.valueOf(inParam.get("environmentUrl"));
    	try {
    		response.setContentType("application/json;charset=UTF-8");
    		//是否存在未结束的job
    		final String preUrl = rb.getString("uc.jenkins.lastjob.preurl");
    		 String jobName = null;
    		/*if ("1".equals(ucEnvironmentType)) {
    			jobName = rb.getString("uc.jenkins.production.jobname");
    		}else if ("2".equals(ucEnvironmentType)) {
    			jobName = rb.getString("uc.jenkins.preproduction.jobname");
    		}else if ("3".equals(ucEnvironmentType)) {
    			jobName = rb.getString("uc.jenkins.test.jobname");
    		}else if ("4".equals(ucEnvironmentType)) {
    			jobName = rb.getString("uc.jenkins.virtual.jobname");
    		}else {
    			jobName = rb.getString("uc.jenkins.aws.jobname");
    		}*/
    		final String lastUrl = rb.getString("uc.jenkins.lastjob.lasturl");
			final String reqUrl = environmentUrl+"/"+buildId+lastUrl;
			final JSONObject json = new JSONObject();
			 //Jenkins服务请求
			String strResult = HttpRequestUtils.httpGet(reqUrl);
			if (strResult!=null&&!"".equals(strResult)) {
				//解析结果集
	    		JSONObject jsonResult = JSONObject.fromObject(strResult);
	    		String building =  String.valueOf(jsonResult.get("building"));
	    		String result =  String.valueOf(jsonResult.get("result"));
	    		//查询结果集
	    		ShareJob shareJob = new ShareJob();
	    		//shareJob.setBuildId(buildId);
	    		List<ShareJob> jobList = shareJobService.queryLimitJob(shareJob);
	    		if ("SUCCESS".equals(result)) {
	    			shareJob.setJobStatus(result);
	    			shareJob.setJobDesc("true");
	    			shareJobService.updateJob(shareJob);
				}
	    		if(result==null||result=="null"){
					shareJob.setJobStatus("building");
					shareJob.setJobDesc(building);
					shareJobService.updateJob(shareJob);
				}
	    		json.put("code", "0");
	    		json.put("building", building);
	    		json.put("result", result);
	    		json.put("jobList", jobList);
	    		json.put("msg", "请求成功");
				response.getWriter().print(json);
				response.getWriter().flush();
			    response.getWriter().close();
			}else{
				json.put("code", "-1");
	    		json.put("msg", "请求成功");
				response.getWriter().print(json);
				response.getWriter().flush();
			    response.getWriter().close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 查询最后一次结果
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 * @return
	 *//*
	@RequestMapping("/queryLastTest")
	@ResponseBody
	public void queryLastTest(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		try {
			response.setContentType("application/json;charset=UTF-8");
			JSONObject json = new JSONObject();
			//查询结果集
			ShareJob shareJob = new ShareJob();
			List<ShareJob> jobList = shareJobService.queryJob(shareJob);
			if (jobList.size()>0) {
				shareJob = jobList.get(0);
			}
			json.put("code", "0");
			json.put("job", shareJob);
			json.put("msg", "请求成功");
			response.getWriter().flush();
		    response.getWriter().close();
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
}
